package com.shuyigou.servlet;

import com.shuyigou.mapper.CustomerMapper;
import com.shuyigou.pojo.Customer;
import com.shuyigou.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //1、获取sqlSessionFactory对象
        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();
        //2、获取sqlSession
        SqlSession sqlSession = sqlSessionFactory.openSession();
        //3、获取Mapper
        CustomerMapper mapper = sqlSession.getMapper(CustomerMapper.class);
        //4、调用方法
        Customer customer = mapper.selectByUsername(username);
        //5、判断是否存在该用户
        if(customer == null) {
            mapper.insertByUsernameAndPassword(username, password);

            sqlSession.commit();
            sqlSession.close();
            resp.sendRedirect("/login.html");

        } else {
            // 用户名存在，给出提示信息
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("用户名已存在");
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
